package com.menu.Service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.menu.Mapper.UserMapper;
import com.menu.Pojo.User;
import com.menu.Service.UserService;
import com.menu.Utils.CommonUtil;
import com.menu.Utils.FileUtils;
import com.menu.Utils.RedisUtil;
import com.menu.Utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private FileUtils fileUtils;
    /**
     * 延迟加载
     */
    @Lazy
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult sendCode(String email) {
        String code =commonUtil.sendEmail(email);
        if (code != null){
            redisUtil.set(email,code,300);
            log.info("{}的验证码发送成功！",email);
            return ResponseResult.success("验证码发送成功！");
        }
        return ResponseResult.error("验证码发送失败，请稍后再试！");
    }

    @Override
    public ResponseResult register(String account, String password, String email, String code) {
        ResponseResult responseResult = verifyAccount(account);
        if (responseResult.getCode() == 501){
            return responseResult;
        }
        responseResult = verifyEmail(email);
        if (responseResult.getCode() == 501){
            return responseResult;
        }
        Object object = redisUtil.get(email);
        if (object == null){
            return ResponseResult.error("验证码已失效！");
        }
        String serverCode = (String) object;
        if (!serverCode.equals(code)){
            return ResponseResult.error("验证码不正确！");
        }
        User user = new User();
        user.setAccount(account);
        user.setPassword(passwordEncoder.encode(password));
        user.setEmail(email);
        user.setHeadImg("https://i1.douguo.com/static/img/70.jpg");
        user.setRegisterTime(new Date(System.currentTimeMillis()));
        Integer integer = userMapper.addUser(user);
        if (integer == 1){
            return ResponseResult.success("注册成功！");
        }else{
            return ResponseResult.error("注册失败，服务器繁忙！");
        }
    }

    @Override
    public ResponseResult verifyAccount(String account) {
        if (userMapper.selectByAccountOrEmail(account,null) != null){
            return ResponseResult.error("账号已存在！");
        }
        return ResponseResult.success("账号合法！");
    }

    @Override
    public ResponseResult verifyEmail(String email) {
        if (userMapper.selectByAccountOrEmail(null,email) != null){
            return ResponseResult.error("邮箱已绑定其他账号！");
        }
        return ResponseResult.success("邮箱合法！");
    }

    @Override
    public ResponseResult findPassword(String email, String code, String newPassword) {
        if (userMapper.selectByAccountOrEmail(null,email) == null){
            return ResponseResult.error("邮箱尚未绑定账号！");
        }
        Object object = redisUtil.get(email);
        if (object == null){
            return ResponseResult.error("验证码已失效！");
        }
        String serverCode = (String) object;
        if (!serverCode.equals(code)){
            return ResponseResult.error("验证码不正确！");
        }
        redisUtil.del(email);
        if (userMapper.updatePassword(email,passwordEncoder.encode(newPassword)) == 1){
            return ResponseResult.success("修改成功！");
        }
        return ResponseResult.error("修改失败，服务器繁忙！");
    }

    @Override
    public ResponseResult getUserInfoById(Integer userId) {
        User user = userMapper.findByUserId(userId);
        user.setPassword(null);
        return ResponseResult.success(user);
    }

    @Override
    public ResponseResult modifyHeadImg(Integer id, MultipartFile multipartFile) {
        ResponseResult responseResult = fileUtils.uploadHeadPhoto(multipartFile, id);
        if (responseResult.getCode() == 200){
            Object object = responseResult.getObject();
            String old = userMapper.findByUserId(id).getHeadImg();
            String headImg = (String) object;
            if (userMapper.modifyHeadImg(id,headImg) == 1){
                if (old != null){
                    fileUtils.deleteFile(old);
                }
                return ResponseResult.success("上传成功！");
            }else{
                fileUtils.deleteFile(headImg);
                return ResponseResult.error("服务器繁忙，请稍后再试！");
            }
        }
        return responseResult;
    }

    @Override
    public ResponseResult selectUserByPage(Integer pageStart, Integer pageSize) {
        PageHelper.startPage(pageStart,pageSize);
        List<User> list = userMapper.selectUserByPage();
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return ResponseResult.success(pageInfo);
    }

    @Override
    public ResponseResult visualSearch(String userInformation,Integer pageStart, Integer pageSize) {
        PageHelper.startPage(pageStart,pageSize);
        List<User> list =userMapper.visualSearch(userInformation);
        PageInfo<User> user = new PageInfo<>(list);
        return ResponseResult.success(user);
    }

    @Override
    public ResponseResult findUserByNameLike(String key, Integer pageNow, Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<User> userList= userMapper.findUserByNameLike(key);
        PageInfo<User> pageInfo=new PageInfo<>(userList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult modifyEmail(Integer userId, String email, String code) {
        Object object = redisUtil.get(email);
        if (object == null){
            return ResponseResult.error("验证码已失效！");
        }
        String serverCode = (String) object;
        if (!serverCode.equals(code)){
            return ResponseResult.error("验证码不正确！");
        }
        User user = userMapper.selectByAccountOrEmail(null,email);
        if (user != null && user.getEmail().equals(email)){
            return ResponseResult.error("两次绑定邮箱相同！");
        }
        if (user != null){
            return ResponseResult.error("该邮箱已被其他用户绑定！");
        }else{
            if (userMapper.updateEmail(userId,email) == 1){
                return ResponseResult.success("修改成功！");
            }else{
                return ResponseResult.error("修改失败，服务器繁忙！");
            }
        }
    }

    @Override
    public ResponseResult modifyPassword(Integer userId, String oldPassword, String newPassword) {
        String password = userMapper.findByUserId(userId).getPassword();
        if (passwordEncoder.matches(oldPassword, password)) {
            log.info("用户:" + userId + "    修改密码！");
            int i = userMapper.modifyPassword(userId, passwordEncoder.encode(newPassword));
            if (i == 1) {
                return ResponseResult.success("修改成功！");
            } else {
                return ResponseResult.error("服务器繁忙，请稍后重试！");
            }
        }
        return ResponseResult.error("旧密码错误！");
    }

    @Override
    public ResponseResult banUserId(Integer userId,Integer state) {
        if (userMapper.modifyUserState(state,userId) == 1){
            return ResponseResult.success("修改成功！");
        }
        return ResponseResult.error("修改失败！");
    }

    @Override
    public ResponseResult findByUserId(Integer userId) {
        User user = userMapper.findByUserId(userId);
        user.setPassword(null);
        if (user == null){
            return ResponseResult.error("查找用户不存在！");
        }
        return ResponseResult.success(user);
    }

    @Override
    public ResponseResult modifyUser(User user) {
        System.out.println(user);
        if (userMapper.modifyUser(user) == 1){
            return ResponseResult.success("修改成功！");
        }
        return ResponseResult.error("服务器繁忙，请稍后再试！");
    }

    @Override
    public ResponseResult rateSex() {
        Map<String, Object> map = userMapper.rateSex();
        if (map == null){
            return ResponseResult.error("查询失败！");
        }
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult rateAge() {
        List<Integer> list = userMapper.rateAge();
        if (list == null){
            return ResponseResult.error("查询失败！");
        }
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult selectByUserId(Integer userId) {
        User user = userMapper.findByUserId(userId);
        if (user == null){
            return ResponseResult.error("用户不存在！");
        }
        return ResponseResult.success(user);
    }
}
